//该路由框架编写者：@3188066816
import { createWebHistory, createRouter } from "vue-router";
import store from'../store/index'
//引入组件
import IndexView from "@/views/IndexView.vue";
import LoginView from "@/views/LoginView.vue";
import RegisView from "@/views/RegisView.vue";
import HomeView from "@/views/HomeView.vue";
//import indexLayout from "@/layout/indexLayout.vue"

const routes = [
    {
        //引入主页面
        path:"/",
        name:'index',
        component:IndexView,
        meta:{requiresAuth:false}//不需要跳转验证
    },
    {
        //跳转登录
        path:"/login",
        name:'login',
        component:LoginView,
        meta:{requiresAuth:false}
    },
    {
        //跳转注册
        path:"/regis",
        name:'regis',
        component:RegisView,
        meta:{requiresAuth:false}
    },
    {
        //跳转主页
        path:"/home",
        name:'home',
        component:HomeView,
        meta:{requiresAuth:true} // 需要登录状态验证
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

//全局路由守卫，验证路由
router.beforeEach((to,from,next)=>{
    // 检查目标路由是否需要认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户是否已登录
    if (store.getters.isLogin==0) {
        // 未登录则重定向到登录页面
            next({
            path: '/login',
            query: { redirect: to.fullPath }  // 保存目标路由，登录后可以跳转回来
            })
        } else {
        // 已登录则继续访问
            next()
        }
        } else {
        // 不需要认证的路由直接放行
        next()
    }
})

export default router; 